<?php

/**
 * UUID 生成
 * @return string
 */
function makeUuid(){
    if (function_exists('com_create_guid')){
        $uuid = com_create_guid();
        $uuid = substr($uuid, 1,  strlen($uuid)-2);
    }else{
        mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
        $charid = strtolower(md5(uniqid(rand(), true)));
        $hyphen = "-";
        $uuid =  substr($charid, 0, 8).$hyphen
                 .substr($charid, 8, 4).$hyphen
                 .substr($charid,12, 4).$hyphen
                 .substr($charid,16, 4).$hyphen
                 .substr($charid,20,12);
    }
    return $uuid;
}
    
/**
 * 生成随机字符串
 * @param int $len 默认长度6
 * @param int $type 生成字符串的类型，必须
 * @param string $addChars 附加字符
 */
function rand_string($len = 6, $type = 4, $addChars = '') { 
    $str = ''; 
    switch ($type) { 
        case 0 : //大小写字母
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars; 
            break; 
        case 1 : //纯数字
            $chars = str_repeat ( '0123456789', 3 ); 
            break; 
        case 2 : //大写字母
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars; 
            break; 
        case 3 : //小写字母
            $chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars; 
            break; 
        case 4 : //默认字符串
            // 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数 
            $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars; 
            break; 
    } 
    if ($len > 10) { //位数过长重复字符串一定次数 
        $chars = $type == 1 ? str_repeat ( $chars, $len ) : str_repeat ( $chars, 5 ); 
    } 
    if ($type != 5) { 
        $chars = str_shuffle ( $chars ); 
        $str = substr ( $chars, 0, $len ); 
    } else { 
        // 中文随机字 
        for($i = 0; $i < $len; $i ++) { 
            $str .= msubstr ( $chars, floor ( mt_rand ( 0, mb_strlen ( $chars, 'utf-8' ) - 1 ) ), 1 ); 
        } 
    } 
    return $str; 
} 

/**
 * 友好的时间显示
 *
 * @param int    $sTime 待显示的时间
 * @param string $type  类型. normal | mohu | full | ymd | other
 * @param string $alt   已失效
 * @return string
 */
function dateFormat($sTime,$type = 'ymd',$alt = 'false') {
    //sTime=源时间，cTime=当前时间，dTime=时间差
    $cTime        =    time();
    $dTime        =    $cTime - $sTime;
    $dDay        =    intval(date("z",$cTime)) - intval(date("z",$sTime));
    //$dDay        =    intval($dTime/3600/24);
    $dYear        =    intval(date("Y",$cTime)) - intval(date("Y",$sTime));
    //normal：n秒前，n分钟前，n小时前，日期
    if($type=='normal'){
        if( $dTime < 60 ){
            return intval($dTime)."秒前";
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
        //今天的数据.年份相同.日期相同.
        }elseif( $dYear==0 && $dDay == 0  ){
            //return intval($dTime/3600)."小时前";
            return '今天'.date('H:i',$sTime);
        }elseif($dYear==0){
            return date("m月d日 H:i",$sTime);
        }else{
            return date("Y-m-d H:i",$sTime);
        }
    }elseif($type=='mohu'){
        if( $dTime < 60 ){
            return intval($dTime)."秒前";
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
        }elseif( $dTime >= 3600 && $dDay == 0  ){
            return intval($dTime/3600)."小时前";
        }elseif( $dDay > 0 && $dDay<=7 ){
            return intval($dDay)."天前";
        }elseif( $dDay > 7 &&  $dDay <= 30 ){
            return intval($dDay/7) . '周前';
        }elseif( $dDay > 30 ){
            return intval($dDay/30) . '个月前';
        }
    //full: Y-m-d , H:i:s
    }elseif($type=='full'){
        return date("Y-m-d  H:i:s",$sTime);
    }elseif($type=='ymd'){
        return date("Y-m-d",$sTime);
    }elseif($type=='md'){
        return date("m-d",$sTime);
    }else{
        if( $dTime < 60 ){
            return intval($dTime)."秒前";
        }elseif( $dTime < 3600 ){
            return intval($dTime/60)."分钟前";
        }elseif( $dTime >= 3600 && $dDay == 0  ){
            return intval($dTime/3600)."小时前";
        }elseif($dYear==0){
            return date("Y-m-d H:i:s",$sTime);
        }else{
            return date("Y-m-d H:i:s",$sTime);
        }
    }
}

/**
 * 字串中间增加星号
 * @param String $str        目标字符串
 * @param int    $len        首尾保留长度
 * @param String $mark       中间替换字符
 * @return String
 */
function _add_asterisk($str = '', $len = 4, $mark = '*'){
    $stra = substr($str, 0, $len);
    $strb = substr($str, strlen($str)-$len);
    $star_num = (strlen($str) - $len * 2) > 4 ? 4 : (strlen($str) - $len * 2);
    $star = '';
    for($i =0;$i < $star_num;$i++){
        $star .= '*';
    }
    return $stra.$star.$strb;
} 

function getWxToken($flush = FALSE){
    $appid = C('WX_APPID');
    $secret = C('WX_SECRET');
    #获取配置文件路径
    $conf_path = C('CONF_PATH');
    #获取accessToken
    $AccessToken = C('WX_ACCESS_TOKEN');

    if ($AccessToken['expires_in'] < time() || $flush) {
        $WechatAuth = new Com\WechatAuth($appid, $secret);
        $token = $WechatAuth->getAccessToken();
        $new_token_arr = array(
                'WX_ACCESS_TOKEN'=> array(
                    'access_token'=>$token['access_token'],
                    'expires_in' => time() + 7000,
                ),
        );
        $config_old = require $conf_path.'/wechat.php';
        $config_new=array_merge($config_old,$new_token_arr);
        arr2file($conf_path.'/wechat.php',$config_new);
    } else {
        $token = $AccessToken;
    }
    return $token['access_token'];
}

// 数组保存到文件
function arr2file($filename, $arr=''){
	if(is_array($arr)){
		$con = var_export($arr,true);
	} else{
		$con = $arr;
	}
	$con = "<?php\nreturn $con;\n?>";//\n!defined('IN_MP') && die();\nreturn $con;\n
	write_file($filename, $con);
}
function mkdirss($dirs,$mode=0777) {
	if(!is_dir($dirs)){
		mkdirss(dirname($dirs), $mode);
		return @mkdir($dirs, $mode);
	}
	return true;
}
function write_file($l1, $l2='',$l3 = ''){
	$dir = dirname($l1);
	if(!is_dir($dir)){
		mkdirss($dir);
	}
        if($l3 == ''){
            return @file_put_contents($l1, $l2);
        }else{
            return @file_put_contents($l1, $l2, FILE_APPEND);
        }
}
function read_file($l1){
	return @file_get_contents($l1);
}

/**
 * 获取openid
 * @param string $code 获取code
 */
function getOpenid($code){
    $appid = C('WX_APPID');
    $appsecret = C('WX_SECRET');
    $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?'
            . 'appid='.$appid
            .'&secret='.$appsecret
            .'&code='.$code
            .'&grant_type=authorization_code';
    $data = get($url);
    return json_decode($data,true);
}

/*
 * HTTP GET Request
*/
function get($url, $param = null) {
    if($param != null) {
        $query = http_build_query($param);
        $url = $url . '?' . $query;
    }   
    $ch = curl_init();
    if(stripos($url, "https://") !== false){
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }   

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    $content = curl_exec($ch);
    $status = curl_getinfo($ch);
    curl_close($ch);
    if(intval($status["http_code"]) == 200) {
        return $content;
    }else{
        echo $status["http_code"];
        return false;
    }   
}

/*
 * HTTP POST Request
*/
function post($url, $params) {
    $ch = curl_init();
    if(stripos($url, "https://") !== false) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    $content = curl_exec($ch);
    $status = curl_getinfo($ch);
    curl_close($ch);
    if(intval($status["http_code"]) == 200) {
        return $content;
    } else {
        echo $status["http_code"];
        return false;
    }
}